<template>
  <div class="trend-container">
      <!-- 顶部导航 -->
      <header class="app-header">
          <!-- Use button like Family.vue -->
            <button class="back-button" @click="router.back()" title="返回">
                <i class="fas fa-arrow-left"></i>
            </button>
            <div class="header-content">
                <h1>{{indicator}}最近趋势</h1>
            </div>
           <!-- Placeholder to balance the back button -->
           <div class="header-placeholder"></div>
      </header>

      <!-- 主要内容区域 -->
      <main class="main-content">
          <!-- 日历组件 -->
          <div class="calendar-section">
              <div class="calendar-header">
                  <i class="fas fa-chevron-left" @click="prevMonth"></i>
                  <span>{{ currentMonthYear }}</span>
                  <i class="fas fa-chevron-right" @click="nextMonth"></i>
              </div>
              <div class="calendar-grid">
                  <div class="weekday" v-for="day in weekDays" :key="day">{{ day }}</div>
                  <div v-for="(date, index) in calendarDates" 
                       :key="index"
                       class="calendar-date"
                       :class="{
                           'has-data': hasData(date),
                           'selected': isSelected(date),
                           'other-month': !isCurrentMonth(date)
                       }"
                       @click="selectDate(date)">
                      <span class="date-number">{{ date.getDate() }}</span>
                      <span v-if="hasData(date)" class="data-value">
                          {{ getDataValue(date) }}
                      </span>
                  </div>
              </div>
          </div>

          <!-- 趋势图表 -->
          <div class="chart-section">
              <div class="chart-header">
                  <h2>30天趋势分析</h2>
                  <div class="chart-legend">
                      <div class="legend-item">
                          <span class="dot normal"></span>
                          <span>正常</span>
                      </div>
                      <div class="legend-item">
                          <span class="dot abnormal"></span>
                          <span>异常</span> 
                      </div>
                  </div>
              </div>
              <div class="chart-container" ref="chartContainer"></div>
          </div>
      </main>

      <!-- 底部导航 -->
      <nav class="bottom-nav">
          <div class="nav-item" :class="{ active: activeTab === 'home' }" @click="router.push('/home')">
              <i class="fas fa-home"></i>
              <span>首页</span>
          </div>
          <div class="nav-item" :class="{ active: activeTab === 'mine' }" @click="router.push('/mine')">
              <i class="fas fa-user"></i>
              <span>我的</span>
          </div>
      </nav>

      <!-- 健康提示区域 -->
      <div class="health-tip">
          <div class="tip-header">
              <i class="fas fa-lightbulb"></i>
              <h3>健康提示</h3>
          </div>
          <div class="tip-content">
              {{ healthTip }}
          </div>
      </div>
  </div>
</template>

<script>
import { ref, onMounted, computed, reactive, toRef } from 'vue';
import { useRouter,useRoute } from 'vue-router';
import * as echarts from 'echarts';
import axios from 'axios';
import { getItem } from '@/components/Session.vue';

export default {
  setup() {
    const route = useRoute();
    const router = useRouter();
    const activeTab = ref('home');
    const chartContainer = ref(null);
    const scope = reactive({
        min: parseInt(route.query.min) || 0,
        max: parseInt(route.query.max) || 0
    });
    let chart = null;
    const healthTip = ref('正在获取健康提示...');
    const indicator = ref(route.query.indicator || '');

    // 日历相关数据
    const currentDate = ref(new Date());
    const selectedDate = ref(new Date());
    const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
    const bloodPressureData = ref([]);

    const currentMonthYear = computed(() => {
        return `${currentDate.value.getFullYear()}年${currentDate.value.getMonth() + 1}月`;
    });
    const user = getItem("user")

    // 获取血压数据
    const fetchBloodPressureData = async (year, month) => {
        try {
            const response = await axios.post('/api/indicator/selectdetail', {
                username: user.username, // 这里应该从用户信息中获取
                indicatorName: route.query.indicator,
                year: year,
                month: month
            });

            if (response.data.code === 200) {
                // 转换数据格式
                bloodPressureData.value = response.data.data.map(item => ({
                    date: item.ymd,
                    value: item.value ? parseInt(item.value) : null
                }));
                updateChart();
            }
        } catch (error) {
            console.error('获取血压数据失败:', error);
        }
    };


    // 获取健康提示
    const fetchHealthTip = async () => {
        try {
            const response = await axios.get('/api/chat/indicatorsuggest', {
                params: {
                    username: user.username, // 这里应该从用户信息中获取
                    indicatorName: route.query.indicator
                }
            });

            if (response.data.code === 200) {
                healthTip.value = response.data.data;
            }
        } catch (error) {
            console.error('获取健康提示失败:', error);
            healthTip.value = '获取健康提示失败，请稍后重试';
        }
    };

    // 日历日期计算
    const calendarDates = computed(() => {
        const year = currentDate.value.getFullYear();
        const month = currentDate.value.getMonth();
        const firstDay = new Date(year, month, 1);
        const lastDay = new Date(year, month + 1, 0);
        const dates = [];

        // 添加上个月的日期
        for (let i = 0; i < firstDay.getDay(); i++) {
            dates.push(new Date(year, month, -i));
        }

        // 添加当前月的日期
        for (let i = 1; i <= lastDay.getDate(); i++) {
            dates.push(new Date(year, month, i));
        }

        // 添加下个月的日期
        const remainingDays = 42 - dates.length;
        for (let i = 1; i <= remainingDays; i++) {
            dates.push(new Date(year, month + 1, i));
        }

        return dates;
    });

    // 日历操作方法
    const prevMonth = () => {
        currentDate.value = new Date(
            currentDate.value.getFullYear(),
            currentDate.value.getMonth() - 1,
            1
        );
        fetchBloodPressureData(
            currentDate.value.getFullYear(),
            currentDate.value.getMonth() + 1
        );
    };

    const nextMonth = () => {
        currentDate.value = new Date(
            currentDate.value.getFullYear(),
            currentDate.value.getMonth() + 1,
            1
        );
        fetchBloodPressureData(
            currentDate.value.getFullYear(),
            currentDate.value.getMonth() + 1
        );
    };

    const isCurrentMonth = (date) => {
        return date.getMonth() === currentDate.value.getMonth();
    };

    const isSelected = (date) => {
        return date.toDateString() === selectedDate.value.toDateString();
    };

    const hasData = (date) => {
        const dateStr = formatDate(date);
        return bloodPressureData.value.some(item => item.date === dateStr && item.value !== null);
    };

    const getDataValue = (date) => {
        const dateStr = formatDate(date);
        const data = bloodPressureData.value.find(item => item.date === dateStr);
        return data && data.value !== null ? `${data.value}` : '';
    };

    const selectDate = (date) => {
        selectedDate.value = date;
        updateChart();
        
        const dateStr = formatDate(date);
        const selectedIndex = bloodPressureData.value.findIndex(item => item.date === dateStr);
        
        if (selectedIndex >= 0 && chart) {
            chart.dispatchAction({
                type: 'showTip',
                seriesIndex: 0,
                dataIndex: selectedIndex
            });
        }
    };

    // 格式化日期为 YYYY-MM-DD
    const formatDate = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    };

    // 初始化图表
    const initChart = () => {
        if (chartContainer.value) {
            chart = echarts.init(chartContainer.value);
            updateChart();
        }
    };

    // 更新图表数据
    const updateChart = () => {
        if (!chart) return;

        const dateStr = formatDate(selectedDate.value);
        const selectedIndex = bloodPressureData.value.findIndex(item => item.date === dateStr);
        
        const option = {
            grid: {
                top: '10%',
                right: '5%',
                bottom: '10%',
                left: '5%',
                containLabel: true
            },
            visualMap: {
                type: 'piecewise',
                show: false,
                pieces: [
                    { min: scope.min, max: scope.max, color: 'rgba(82, 196, 26, 1)' }
                ],
                outOfRange: {
                    color: 'rgba(255, 77, 79, 1)'
                }
            },
            tooltip: {
                trigger: 'axis',
                formatter: function(params) {
                    const data = bloodPressureData.value[params[0].dataIndex];
                    return `日期：${data.date}<br/>
                            数值：${data.value !== null ? data.value + ' mmHg' : '无数据'}`;
                }
            },
            xAxis: {
                type: 'category',
                data: bloodPressureData.value.map(item => item.date ? item.date.split('-')[2] + '日' : ''),
                axisLine: {
                    lineStyle: {
                        color: '#999'
                    }
                }
            },
            yAxis: {
                type: 'value',
                name: 'mmHg',
                min: indicator.value === '体温' ? scope.min - 1 : indicator.value === '血糖' ? scope.min - 5 : scope.min - 50,
                max: indicator.value === '体温' ? scope.max + 1 : indicator.value === '血糖' ? scope.max + 5 : scope.max + 50,
                axisLine: {
                    lineStyle: {
                        color: '#999'
                    }
                },
                splitLine: {
                    lineStyle: {
                        color: '#eee'
                    }
                }
            },
            series: [
                {
                    name: indicator.value,
                    type: 'line',
                    data: bloodPressureData.value.map(item => item.value),
                    itemStyle: {
                        color: function(params) {
                            return params.value > scope.max || params.value < scope.min ? '#ff4d4f' : '#52c41a';
                        }
                    },
                    lineStyle: {
                        width: 3
                    },
                    symbol: 'none',
                    symbolSize: 8,
                    emphasis: {
                        scale: true,
                        focus: 'series',
                        itemStyle: {
                            symbol: 'circle',
                            color: function(params) {
                                return params.value > scope.max || params.value < scope.min ? '#ff4d4f' : '#52c41a';
                            }
                        }
                    }
                }
            ]
        };

        chart.setOption(option);
    };

    onMounted(() => {
        initChart();
        fetchBloodPressureData(
            currentDate.value.getFullYear(),
            currentDate.value.getMonth() + 1
        );
        fetchHealthTip();
        window.addEventListener('resize', () => {
            chart && chart.resize();
        });
    });

    return {
      indicator,
      router,
      activeTab,
      currentMonthYear,
      weekDays,
      calendarDates,
      chartContainer,
      healthTip,
      prevMonth,
      nextMonth,
      isCurrentMonth,
      isSelected,
      hasData,
      getDataValue,
      selectDate,
      scope
    };
  }
}
</script>

<style scoped>
.trend-container {
  min-height: 100vh;
  max-width: 100vw;
  width: 100%;
  background-color: #f8f9fa;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow-x: hidden;
  padding-bottom: 30vw; /* 为底部导航和健康提示留出空间 */
}

.app-header {
  background: linear-gradient(135deg, #4CAF50, #2196F3);
  color: white;
  padding: 4vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-button {
    background: none;
    border: none;
    color: white;
    font-size: 5vw;
    cursor: pointer;
    padding: 2vw;
    margin-left: -2vw;
    line-height: 1;
}

.back-button:hover {
    opacity: 0.8;
}

.header-content {
    text-align: center;
    flex-grow: 1;
}

.header-content h1 {
    color: white;
    font-size: 4.5vw;
    font-weight: 600;
    margin: 0;
}

.header-placeholder {
    width: 10vw;
    visibility: hidden;
}

.main-content {
  flex: 1;
  padding: 4vw;
  padding-bottom: 20vw;
}

/* 日历样式 */
.calendar-section {
  background: white;
  border-radius: 3vw;
  padding: 3vw;
  margin-bottom: 4vw;
  box-shadow: 0 0.5vw 2vw rgba(0, 0, 0, 0.05);
  max-width: 90%;
  margin-left: auto;
  margin-right: auto;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 3vw;
}

.calendar-header span {
  font-size: 3.5vw;
  font-weight: 600;
  color: #333;
}

.calendar-header i {
  font-size: 3.5vw;
  color: #666;
  cursor: pointer;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 1.5vw;
}

.weekday {
  text-align: center;
  font-size: 2.5vw;
  color: #999;
  padding: 1.5vw 0;
}

.calendar-date {
  aspect-ratio: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 1.5vw;
  cursor: pointer;
  position: relative;
  padding: 0.8vw;
}

.date-number {
  font-size: 3vw;
  color: #333;
}

.other-month .date-number {
  color: #ccc;
}

.has-data {
  background-color: #e8f5e9;
}

.selected {
  background-color: #4CAF50;
}

.selected .date-number {
  color: white;
}

.data-value {
  font-size: 2vw;
  color: #4CAF50;
  margin-top: 0.5vw;
}

.selected .data-value {
  color: white;
}

/* 图表样式 */
.chart-section {
  background: white;
  border-radius: 3vw;
  padding: 4vw;
  box-shadow: 0 0.5vw 2vw rgba(0, 0, 0, 0.05);
  margin-top: 2vw;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4vw;
}

.chart-header h2 {
  font-size: 4vw;
  margin: 0;
  color: #333;
}

.chart-legend {
  display: flex;
  flex-direction: column;
  gap: 2vw;
  font-size: 3vw;
  color: #666;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 2vw;
}

.dot {
  width: 3vw;
  height: 3vw;
  border-radius: 50%;
}

.dot.normal {
  background-color: #52c41a;
}

.dot.abnormal {
  background-color: #ff4d4f;
}

.chart-container {
  width: 100%;
  height: 80vw;
}

/* 底部导航 */
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 15vw;
  background: white;
  display: flex;
  justify-content: space-around;
  align-items: center;
  box-shadow: 0 -0.5vw 2vw rgba(0, 0, 0, 0.05);
  z-index: 2;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1vw;
  color: #666;
  font-size: 3vw;
  cursor: pointer;
}

.nav-item i {
  font-size: 5vw;
}

.nav-item.active {
  color: #2196F3;
}

.nav-item.active i {
  transform: scale(1.1);
}

/* 响应式调整 */
@media screen and (max-width: 320px) {
  .calendar-date {
      padding: 0.5vw;
  }

  .date-number {
      font-size: 3vw;
  }

  .data-value {
      font-size: 2vw;
  }

  .chart-container {
      height: 50vw;
  }
}

.health-tip {
    background: white;
    border-radius: 3vw;
    padding: 4vw;
    margin: 4vw;
    box-shadow: 0 0.5vw 2vw rgba(0, 0, 0, 0.05);
    position: relative;
    z-index: 1;
}

.tip-header {
    display: flex;
    align-items: center;
    gap: 2vw;
    margin-bottom: 3vw;
}

.tip-header i {
    color: #ffc107;
    font-size: 5vw;
}

.tip-header h3 {
    font-size: 4vw;
    color: #333;
    margin: 0;
}

.tip-content {
    font-size: 3.5vw;
    color: #666;
    line-height: 1.5;
}
</style>